package com.sgam.mf.reports;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfTable;
import com.sgam.mf.domain.entity.ApplicationProjectType;
import com.sgam.mf.domain.entity.ApplicationPropertyType;
import com.sgam.mf.domain.entity.ContractAddAgree;
import com.sgam.mf.domain.entity.Contracts;
import com.sgam.mf.helper.ProxyCurrentUser;
import com.sgam.mf.service.entity.ContractsService;

@Service
public class DownloadServiceImpl implements DownloadService {

	protected static Logger logger = Logger.getLogger("service");

	//@Autowired private JasperDatasourceService datasource;

	@Autowired
	private ExporterService exporter;

	@Autowired
	private TokenService tokenService;
	

	@Override
	public void download(Integer orderId, String type, String token, HttpServletResponse response) {
		
		Connection conn = getConnection();

		try {
			// 1. Add report parameters
			HashMap<String, Object> params = new HashMap<String, Object>(); 
			params.put("Title", "User Report");
			params.put("P_ORDER_ID", orderId);

			// 2.  Retrieve template
			InputStream reportStream = this.getClass().getResourceAsStream(TEMPLATE); 
 
			// 3. Convert template to JasperDesign
			JasperDesign jd = JRXmlLoader.load(reportStream);

			// 4. Compile design to JasperReport
			JasperReport jr = JasperCompileManager.compileReport(jd);

			// 5. Create the JasperPrint object
			// Make sure to pass the JasperReport, report parameters, and data source
			JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);//, datasource.getDataSource());
 
			// 6. Create an output byte stream where data will be written
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			// 7. Export report
			exporter.export(type, jp, response, baos);

			// 8. Write to reponse stream
			write(token, response, baos);

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("Failed to make connection!");
			}
			
			
			
		} catch (JRException jre) {
			logger.error("Unable to process download");
			throw new RuntimeException(jre);
		}
	}
	
	public void testItext(HttpServletResponse response){
		ServletOutputStream outputStream;
		ByteArrayOutputStream baos; 
		
		PdfReader pdfTemplate; 
		
		float imgPosX = 0, imgPosY = 0;
		
		try {
			pdfTemplate = new PdfReader("/itextTemplate.pdf"); 
			baos = new ByteArrayOutputStream();
			
			PdfStamper stamper = new PdfStamper(pdfTemplate, baos);

			stamper.setFormFlattening(true);
			
			
			AcroFields form = stamper.getAcroFields();
			String s = "TEST TEXT";
			form.setField("testField", 	s);
			
			
			URL imageUrl = getClass().getResource("/HeaderMF.png");
			//URL imageUrl = getClass().getResource("/EGClogo.jpg");
			
			Image img = Image.getInstance(imageUrl);
			
			img.scaleToFit(595, 842);
			
			if (img.getPlainHeight() < 842 ) {
				imgPosY = 842 - img.getPlainHeight(); 
			}
			
			if (img.getPlainWidth() < 595 ) {
				imgPosY = 595 - img.getPlainWidth(); 
			}
			
			img.setAbsolutePosition(imgPosX, imgPosY);
			
			
			
			PdfContentByte  under = stamper.getUnderContent(1);
			under.addImage(img);
			
			stamper.close();
			pdfTemplate.close();
			
			outputStream = response.getOutputStream();
			
			
			// Write to output stream
			baos.writeTo(outputStream);
			// Flush the stream
			outputStream.flush();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	
	public  void getReportContractsList(HttpServletResponse response, 
										ProxyCurrentUser user, 
										String type, 
										String token,
										String  dateFrom,
										String  dateTo, 
										String  regionId,
										String  servicesString){
		
		Connection conn = getConnection();
		String userWhere = " 1 = 0 ";
		try {
		
			
			// 1. Add report parameters
			HashMap<String, Object> params = new HashMap<String, Object>(); 
			//params.put("Title", "User Report");
			//params.put("P_ORDER_ID", orderId);
			params.put("dateFrom", dateFrom);
			params.put("dateTo", dateTo);
			params.put("regionId", regionId);
			params.put("servicesString", servicesString);
			
			if (user.getUserRoleId() == 0 ||user.getUserRoleId() == 1) {// Daca useru e Admin sau Manbager
				userWhere = " 1 = 1 "; //filtru e gol
			} else {
				userWhere = "  consultant_id = " + user.getUserId() + " or personal_id = " + user.getUserId() + " or  personal2_id  = " + + user.getUserId() + " ";
			}
			params.put("userWhere", userWhere);

			// 2.  Retrieve template
			InputStream reportStream = this.getClass().getResourceAsStream("/reportContracte.jrxml"); 
 
			// 3. Convert template to JasperDesign
			JasperDesign jd = JRXmlLoader.load(reportStream);

			// 4. Compile design to JasperReport
			JasperReport jr = JasperCompileManager.compileReport(jd);

			// 5. Create the JasperPrint object
			// Make sure to pass the JasperReport, report parameters, and data source
			JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);//, datasource.getDataSource());
 
			// 6. Create an output byte stream where data will be written
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			// 7. Export report
			exporter.export(type, jp, response, baos);

			// 8. Write to reponse stream
			write(token, response, baos);

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("Failed to make connection!");
			}
			
			
			
		} catch (JRException jre) {
			logger.error("Unable to process download");
			throw new RuntimeException(jre);
		}
		
	}
	

	public  void getReportAsigurariList(HttpServletResponse response, 
			ProxyCurrentUser user, 
			String type, 
			String token,
			String  dateFrom,
			String  dateTo){

		Connection conn = getConnection();
		String userWhere = " 1 = 0 ";
		try {
		
			// 1. Add report parameters
			HashMap<String, Object> params = new HashMap<String, Object>(); 
			//params.put("Title", "User Report");
			//params.put("P_ORDER_ID", orderId);
			params.put("dateFrom", dateFrom);
			params.put("dateTo", dateTo);
					
			if (user.getUserRoleId() == 0 ||user.getUserRoleId() == 1) {// Daca useru e Admin sau Manbager
				userWhere = " 1 = 1 "; //filtru e gol
			} 
			params.put("userWhere", userWhere);
			
			// 2.  Retrieve template
			InputStream reportStream = this.getClass().getResourceAsStream("/reportAsigurari.jrxml"); 
			
			// 3. Convert template to JasperDesign
			JasperDesign jd = JRXmlLoader.load(reportStream);
			
			// 4. Compile design to JasperReport
			JasperReport jr = JasperCompileManager.compileReport(jd);
			
			// 5. Create the JasperPrint object
			// Make sure to pass the JasperReport, report parameters, and data source
			JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);//, datasource.getDataSource());
			
			// 6. Create an output byte stream where data will be written
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			// 7. Export report
			exporter.export(type, jp, response, baos);
			
			// 8. Write to reponse stream
			write(token, response, baos);
			
			if (conn != null) {
					try {
							conn.close();
						} 
					catch (SQLException e) {
							e.printStackTrace();
					}
				} 
			else {
				System.out.println("Failed to make connection!");
			}
		
		} catch (JRException jre) {
			logger.error("Unable to process download");
			throw new RuntimeException(jre);
		}
	
	}	
	
	
	public  void getReportPaymentsList(HttpServletResponse response, 
			ProxyCurrentUser user, 
			String type, 
			String token,
			String  dateFrom,
			String  dateTo,
			String  pUtype,
			String  pUid){

		Connection conn = getConnection();
		String userWhere = " 1 = 0 ";
		try {
		
			// 1. Add report parameters
			HashMap<String, Object> params = new HashMap<String, Object>(); 
			//params.put("Title", "User Report");
			//params.put("P_ORDER_ID", orderId);
			params.put("dateFrom", dateFrom);
			params.put("dateTo", dateTo);
					
			if (user.getUserRoleId() == 0 ||user.getUserRoleId() == 1) {// Daca useru e Admin sau Manbager
				
				if (pUtype != null && pUtype.length() > 0 && pUid != null && pUid.length() > 0) { //если пришла ПАРА параметров pUid и pUtype - добавляем в фильтр 
					userWhere = " upper(utype) = upper('" + pUtype +"' ) and uid = " + pUid + " ";
				} else {
					userWhere = " 1 = 1 "; //filtru e gol	
				}
				
				
				
			} else { 
				userWhere = " uid = " + user.getUserId().toString() + " "; // показываем только записи которые касаются самого юзера
			}
			params.put("userWhere", userWhere);
			
			// 2.  Retrieve template
			InputStream reportStream = this.getClass().getResourceAsStream("/reportContractePayments.jrxml"); 
			
			// 3. Convert template to JasperDesign
			JasperDesign jd = JRXmlLoader.load(reportStream);
			
			// 4. Compile design to JasperReport
			JasperReport jr = JasperCompileManager.compileReport(jd);
			
			// 5. Create the JasperPrint object
			// Make sure to pass the JasperReport, report parameters, and data source
			JasperPrint jp = JasperFillManager.fillReport(jr, params, conn);//, datasource.getDataSource());
			
			// 6. Create an output byte stream where data will be written
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			// 7. Export report
			exporter.export(type, jp, response, baos);
			
			// 8. Write to reponse stream
			write(token, response, baos);
			
			if (conn != null) {
					try {
							conn.close();
						} 
					catch (SQLException e) {
							e.printStackTrace();
					}
				} 
			else {
				System.out.println("Failed to make connection!");
			}
		
		} catch (JRException jre) {
			logger.error("Unable to process download");
			throw new RuntimeException(jre);
		}
	
	}	
	
	
	@Autowired  ContractsService  contractsService;
	
	@SuppressWarnings({ "unused", "unchecked" })
	public void generateContractItext(HttpServletResponse response, Integer contractId, String contractTemplateName, String  printBackground, ProxyCurrentUser user){
		Contracts item = contractsService.get(contractId, user);
		
		ServletOutputStream outputStream;
		ByteArrayOutputStream baos; 
		
		PdfReader pdfTemplate; 
		
		float imgPosX = 0, imgPosY = 0;
		
		try {
			
			pdfTemplate = new PdfReader("/reports/" + contractTemplateName + ".pdf");
			
			baos = new ByteArrayOutputStream();
			
			PdfStamper stamper = new PdfStamper(pdfTemplate, baos);

			stamper.setFormFlattening(true);
			
			/* FILLLLLING FORM VALUES */
			
			AcroFields form = stamper.getAcroFields();
			
			HashMap<String, AcroFields.Item> mp = form.getFields();
			
			Iterator mpIt = mp.entrySet().iterator();
		
			while (mpIt.hasNext()) {
		        Map.Entry<String, AcroFields.Item> pairs = (Map.Entry<String, AcroFields.Item>)mpIt.next();
		        
		        String fieldName = pairs.getKey().toString();
		        String fieldNameOriginal = fieldName;
		        fieldName = fieldName.replace("_dbl5", "");
		        fieldName = fieldName.replace("_dbl4", "");
		        fieldName = fieldName.replace("_dbl3", "");
		        fieldName = fieldName.replace("_dbl2", "");
		        fieldName = fieldName.replace("_dbl1", "");
		        fieldName = fieldName.replace("_dbl", "");
		        String fieldValue = "";
		        
		        logger.debug("====================================================");	
		        logger.debug("FORM FIELD FULL NAME	: " + fieldName);
		        
		        if (fieldName.equalsIgnoreCase("applicationPropertyType")) {
		        	fieldValue = getApplicationPropertyTypeListAsString(item);
		        } else {
		        	if (fieldName.equalsIgnoreCase("applicationProjectType")) {
		        		fieldValue = getApplicationProjectTypeListAsString(item);
		        	} else {
		        		if  (fieldName.equalsIgnoreCase("sysdate")) {
		        			DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
		        			fieldValue = formatter.format( new Date());
		        					
		        		} else {
		        			fieldValue = getOneFieldValue (fieldName, item);	
		        		}
		        	}
		        }

		        form.setField(fieldNameOriginal , fieldValue);
		    } 

			
		    //Add Table for predefined types of report "1acord", "2acord" 
		    if (contractTemplateName.equalsIgnoreCase("1acord") || contractTemplateName.equalsIgnoreCase("2acord")) {
		    	PdfContentByte  canvas = stamper.getOverContent(1);
				PdfPTable table = getContractAddAgreeTable(item.getContractAddAgree());
				table.writeSelectedRows(0,-1,50,475, canvas);
		    }
			
			
			/* FILLLLLING  WITH LOGO IMAGE IN DEPENDENCY OF refCompany*/
		    if (printBackground.equalsIgnoreCase("1")) {
		    	String fillLogoFileName =  item.getRefCompany().getLogoname();
				URL imageUrl = null; 
			    if ( fillLogoFileName != null && fillLogoFileName.length() > 0){
			    	imageUrl = getClass().getResource("/" + fillLogoFileName);
			    }
				//URL imageUrl = getClass().getResource("/HeaderMF.png");
				//URL imageUrl = getClass().getResource("/EGClogo.jpg");
				Image img = Image.getInstance(imageUrl);
				img.scaleToFit(595, 842);
				if (img.getPlainHeight() < 842 ) { imgPosY = 842 - img.getPlainHeight(); }
				if (img.getPlainWidth() < 595 ) { imgPosY = 595 - img.getPlainWidth();}
				img.setAbsolutePosition(imgPosX, imgPosY);
				PdfContentByte  under = stamper.getUnderContent(1);
				under.addImage(img);
		    }
			
		  
		    
			
			stamper.close();
			pdfTemplate.close();
			
			outputStream = response.getOutputStream();
			
			
			// Write to output stream
			baos.writeTo(outputStream);
			// Flush the stream
			outputStream.flush();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	 public static PdfPTable getContractAddAgreeTable(List<ContractAddAgree> contractAddAgreeList) throws DocumentException {
		 

	        PdfPTable table = new PdfPTable(4);
	        table.setTotalWidth(500);
	        table.setWidths(new int[]{170, 170, 80, 80});
	        //Add HEADER
	        Font headerFont = new Font(Font.COURIER, 8, Font.BOLD, Color.BLACK);
	        
	        PdfPCell cell;
	        
	        cell = new PdfPCell(new Phrase("COMPANIILE - PARTENERI", headerFont));
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        cell.setBackgroundColor(Color.LIGHT_GRAY);
	        cell.setMinimumHeight(20);
	        table.addCell(cell);
	        
	        cell = new PdfPCell(new Phrase("BUNURI PROCURATE", headerFont));
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        cell.setBackgroundColor(Color.LIGHT_GRAY);
	        table.addCell(cell);
	        
	        cell = new PdfPCell(new Phrase("SUMA TRANSFERULUI", headerFont));
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        cell.setBackgroundColor(Color.LIGHT_GRAY);
	        table.addCell(cell);
	        
	        cell = new PdfPCell(new Phrase("DATA TRANSFERULUI", headerFont));
	        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        cell.setBackgroundColor(Color.LIGHT_GRAY);
	        table.addCell(cell);
	        
	        Font dataFont = new Font(Font.COURIER, 9, Font.NORMAL, Color.BLACK);
	        
	        for (ContractAddAgree contractAddAgreeItem : contractAddAgreeList) {
	        	
	        	PdfPCell companyCell = new PdfPCell( new Phrase( contractAddAgreeItem.getRegPartners().getCompanyName(), dataFont ));
	        	companyCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        	companyCell.setPaddingLeft(5);
	        	table.addCell(companyCell);
	        	
	        	PdfPCell goodsCell = new PdfPCell( new Phrase( contractAddAgreeItem.getGoods(), dataFont ));
	        	goodsCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	        	goodsCell.setPaddingLeft(5);
	        	table.addCell(goodsCell);
	        	
	        	PdfPCell amountCell = new PdfPCell( new Phrase( contractAddAgreeItem.getAmount().toString(), dataFont ));
	        	amountCell.setVerticalAlignment(PdfTable.ALIGN_MIDDLE);
	        	amountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
	        	amountCell.setPaddingRight(5);
	        	table.addCell(amountCell);
		        
	        	DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    			String dateTransCellString = "";
    			if (contractAddAgreeItem.getDateTrans() != null) {
    				dateTransCellString = formatter.format(contractAddAgreeItem.getDateTrans());
    			}
    			
	        	PdfPCell dateTransCell = new PdfPCell( new Phrase( dateTransCellString , dataFont ));
	        	dateTransCell.setVerticalAlignment(PdfTable.ALIGN_MIDDLE);
	        	dateTransCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	        	table.addCell(dateTransCell);
	        }
	        
	        
	        
	        return table;
	    }
	
	private String getApplicationPropertyTypeListAsString(Contracts contractItem)   {
		List<ApplicationPropertyType> propertiesList = contractItem.getApplicationPropertyType();  
		String result = "";
		for (ApplicationPropertyType tempItem : propertiesList) {
			result = result + (tempItem.getValue()==1?"[X] - ":"[  ] - ") + tempItem.getRefPropertyType().getMdValue() + "\n";
		}
		return result;
	}
	
	private String getApplicationProjectTypeListAsString(Contracts contractItem)   {
		List<ApplicationProjectType> projectsList = contractItem.getApplicationProjectType();  
		String result = "";
		for (ApplicationProjectType tempItem : projectsList) {
			result = result + (tempItem.getValue()==1?"[X] - ":"[  ] - ") + tempItem.getRefProjectType().getMdValue()+ "\n";
		}
		return result;
	}
	
	private String getOneFieldValue (String fieldName, Object entityItem){
		String result = "";
		String[] splittedFieldName;
		int		 fieldNameLevel = 0;
		    		
    	logger.debug( "Form Field Actual Name       fieldName = " + fieldName);
    	logger.debug( "Object Class Name            entityItem.getClass() = " + entityItem.getClass());
    	
    	splittedFieldName = fieldName.split("\\.");
    	fieldNameLevel = splittedFieldName.length;
    	
   	    	
    	try {
			String prop = Character.toUpperCase(splittedFieldName[0].charAt(0)) + splittedFieldName[0].substring(1);
			String mname = "get" + prop;
			Class[] types = new Class[] {};
			Method method = entityItem.getClass().getMethod(mname, types);
			
			String methodName		= method.getName();
			String methodReturnType = method.getReturnType().getSimpleName();
			
			logger.debug("Method Name  = " + 			methodName);
			logger.debug("Method Return Type   = " + 	methodReturnType);	
			
			if (	   methodReturnType.contentEquals("Date")   || methodReturnType.contentEquals("String") 
					|| methodReturnType.contentEquals("Object") || methodReturnType.contentEquals("Long") 
					|| methodReturnType.contentEquals("Double") || methodReturnType.contentEquals("Integer") 
					|| methodReturnType.contentEquals("Float")  || methodReturnType.contentEquals("Boolean")) {
				Object value = method.invoke(entityItem, new Object[0]);
				 if (value != null) {
			        	if (methodReturnType.contentEquals("Date")) {
				        	// Обработка поля типа Дата
			        			String dataTimePattern = "dd.MM.yyyy";// method.getAnnotation(DateTimeFormat.class).pattern();
				        		if (dataTimePattern != null) {
				        			DateFormat formatter = new SimpleDateFormat(dataTimePattern);
					        		result = formatter.format((Date)value);
					        		return result;
				        		} else {
				        			result = value.toString();
				        			return result;
				        		}
			        	} else {
				        	// Обработка поля других типов
				        		result = value.toString();
				        		return result;
			        	}
					}
				 
			} else {
				String cuttedFieldName = fieldName.replace(splittedFieldName[0]+".", "");
				Object innerObject = method.invoke(entityItem, new Object[0]);
				if (cuttedFieldName!= null && innerObject!= null){
					result = getOneFieldValue (cuttedFieldName, innerObject);	
				}
				return result;
			}

    	} catch (SecurityException e) {
			
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return result;
	}
	

	private String getOneFieldValueZZ (String fieldName, Object entityItem){
		String result = "";
		String[] splittedFieldName;
		int		 fieldNameLevel = 0;
		    		
    	logger.debug( "Form Field Actual Name       fieldName = " + fieldName);
    	logger.debug( "Object Class Name            entityItem.getClass() = " + entityItem.getClass());
    	logger.debug( "Object SUPER Class Name      entityItem.getClass().getSuperclass() = " + entityItem.getClass().getSuperclass());
    	logger.debug( "Object SUPER Class Name      entityItem.getClass().getSuperclass().getCanonicalName() = " + entityItem.getClass().getSuperclass().getCanonicalName().equalsIgnoreCase("java.lang.Object"));
    	
    	splittedFieldName = fieldName.split("\\.");
    	fieldNameLevel = splittedFieldName.length;
    	
   	    try {
   	    	
   	    	
    	    	for (Field field : entityItem.getClass().getDeclaredFields()) {
			    	
    	    		field.setAccessible(true); // You might want to set modifier to public first.
    	    		
    	    		if (    !entityItem.getClass().getSuperclass().getCanonicalName().equalsIgnoreCase("java.lang.Object") && 
    	        			!entityItem.getClass().getSuperclass().getCanonicalName().equalsIgnoreCase("java.lang.Class")      ) {
    	        		getOneFieldValue(fieldName, field.get(entityItem));
    	        	}
    	    		
			    	
				    	if (splittedFieldName[0].equalsIgnoreCase(field.getName() )) {
				    		// Проверка специализированных типов
							String type = field.getType().getSimpleName();
							if (type.contentEquals("Date")  || type.contentEquals("String") 
															|| type.contentEquals("Object")
															|| type.contentEquals("Long") 
															|| type.contentEquals("Double") 
															|| type.contentEquals("Integer") 
															|| type.contentEquals("Float") 
															|| type.contentEquals("Boolean")) {
						        Object value = field.get(entityItem);
						        if (value != null) {
						        	if (type.contentEquals("Date")) {
							        	// Обработка поля типа Дата
						        			String dataTimePattern = field.getAnnotation(DateTimeFormat.class).pattern();
							        		if (dataTimePattern != null) {
							        			DateFormat formatter = new SimpleDateFormat(dataTimePattern);
								        		result = formatter.format((Date)value);
								        		return result;
							        		} else {
							        			result = value.toString();
							        			return result;
							        		}
						        	} else {
							        	// Обработка поля других типов
							        		result = value.toString();
							        		return result;
						        	}
								}
							} else {
								
								String cuttedFieldName = fieldName.replace(splittedFieldName[0]+".", "");
								Object innerObject = field.get(entityItem);
								if (cuttedFieldName!= null && innerObject!= null){
									result = getOneFieldValue (cuttedFieldName, innerObject);	
								}
								return result;
								
								
							}
				    	}
    	    	}
/* -------------------------------------------------------------------------------------- */
    	    	
			    
	    } catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}     	

    	logger.debug( "Calculated RESULT  = " + result);
		return result;
	}
		
	
	
	private Connection getConnection(){
		Connection connection = null;
		
		System.out.println("-------- PostgreSQL  JDBC Connection Testing ------------");
 
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("Where is your PostgreSQL JDBC Driver? "
					+ "Include in your library path!");
			e.printStackTrace();
			return connection;
		}
 
		System.out.println("PostgreSQL JDBC Driver Registered!");
		try {
   
			connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost:5432/magfin", "mf", "mf");
//					"jdbc:postgresql://192.168.11.237:5432/magfin", "mf", "mf");
 
		} catch (SQLException e) {
 
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return connection;
 
		}
 
		if (connection != null) {
			System.out.println("You made it, take control your database now!");
		} else {
			System.out.println("Failed to make connection!");
		} 
		
		return connection;
	}
	
	
	/**
	* Writes the report to the output stream
	*/
	private void write(String token, HttpServletResponse response,
			ByteArrayOutputStream baos) {

		try {
			logger.debug(baos.size());

			// Retrieve output stream
			ServletOutputStream outputStream = response.getOutputStream();
			// Write to output stream
			baos.writeTo(outputStream);
			// Flush the stream
			outputStream.flush();

			// Remove download token
			tokenService.remove(token);

		} catch (Exception e) {
			logger.error("Unable to write report to the output stream");
			throw new RuntimeException(e);
		}
	}
}
